package com.cap6402.project.two;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.R;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class MainMenuActivity extends Activity implements OnClickListener {
	private SharedPreferences mPrefs;
	private CustomButton playButton, facebookButton, aboutButton;
	private Handler mHandler = new Handler();
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        // Create the Facebook Object using the app id.
        Utility.mFacebook = new Facebook(Utility.APP_ID);
        // Instantiate the asynrunner object for asynchronous api calls.
        Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
        
        playButton = (CustomButton) MainMenuActivity.this.findViewById(R.id.playButton);
        facebookButton = (CustomButton) MainMenuActivity.this.findViewById(R.id.facebookButton);
        aboutButton = (CustomButton) MainMenuActivity.this.findViewById(R.id.aboutButton);
        
        /*
         * Get existing access_token if any
         */
        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
        if(access_token != null) {
            Utility.mFacebook.setAccessToken(access_token);
            facebookButton.updateImage(R.drawable.logout_button);
        } else {
        	 playButton.setEnabled(false);
        }
        if(expires != 0) {
            Utility.mFacebook.setAccessExpires(expires);
        }
        
        facebookButton.setOnClickListener(this);
        playButton.setOnClickListener(this);
        aboutButton.setOnClickListener(this);
        
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
    }
	@Override
	public void onClick(View view) {
		CustomButton btn = (CustomButton) view;
		if(btn.equals(aboutButton)) {
			Intent intent = new Intent(this, AboutPageActivity.class);
			startActivity(intent);
		}
		if(btn.equals(playButton)) {
			Intent intent = new Intent(this, ChooseLevelActivity.class);
			startActivity(intent);
		}
		if(btn.equals(facebookButton)) {
	        /*
	         * Only call authorize if the access_token has expired.
	         */
	        if(!Utility.mFacebook.isSessionValid()) {

	            Utility.mFacebook.authorize(this, new String[] {}, new DialogListener() {
	                @Override
	                public void onComplete(Bundle values) {
	                    SharedPreferences.Editor editor = mPrefs.edit();
	                    editor.putString("access_token", Utility.mFacebook.getAccessToken());
	                    editor.putLong("access_expires", Utility.mFacebook.getAccessExpires());
	                    editor.commit();
	                    playButton.setEnabled(true);
	                    facebookButton.updateImage(R.drawable.logout_button);
	                }
	    
	                @Override
	                public void onFacebookError(FacebookError error) {Log.e("Graph Game",error.toString());}
	    
	                @Override
	                public void onError(DialogError e) {Log.e("Graph Game",e.toString());}
	    
	                @Override
	                public void onCancel() {}
	            });
	        } else {
	        	Utility.mAsyncRunner.logout(this, new RequestListener() {
	        		@Override
	        		public void onComplete(String response, Object state) {
	        			mHandler.post(new Runnable() {
							@Override
							public void run() {
			        			playButton.setEnabled(false);
			        			facebookButton.updateImage(R.drawable.facebook_button);
			        			 SharedPreferences.Editor editor = mPrefs.edit();
			        			 editor.remove("access_token");
			        			 editor.remove("access_expires");
			        			 editor.commit();
							}
	        			});
	        		}


	        		@Override
	        		public void onFacebookError(FacebookError e, Object state) {}

	        		@Override
	        		public void onIOException(IOException e, Object state) {
	        			// TODO Auto-generated method stub

	        		}

	        		@Override
	        		public void onFileNotFoundException(
	        				FileNotFoundException e, Object state) {
	        			// TODO Auto-generated method stub

	        		}

	        		@Override
	        		public void onMalformedURLException(
	        				MalformedURLException e, Object state) {
	        			// TODO Auto-generated method stub

	        		}
	        	});
	        }
	        return;
		}

	}
}
